package com.rcl.mvvmdemo.musicList

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.rcl.mvvmdemo.lifecycle.AbsLifecycle
import com.rcl.mvvmdemo.lifecycle.ILifecycle
import com.rcl.mvvmdemo.lifecycle.ILifecycleOwner
import com.rcl.mvvmdemo.lifecycle.LifecycleState
import com.rcl.mvvmdemo.player.DataListenerContainer
import com.rcl.mvvmdemo.player.domain.Music

class MusicsPresenter(owner: LifecycleOwner) {

    private val viewLifeImpl by lazy {
        ViewLifeImpl()
    }

    init {
        owner.lifecycle.addObserver(viewLifeImpl)
    }

    private val musicModel by lazy {
        MusicsModel()
    }

    val liveMusicList = MutableLiveData<List<Music>>()
    val musicList = DataListenerContainer<List<Music>>()

    enum class MusicLoadState {
        LOADING, EMPTY, SUCCESS, ERROR

    }

    val loadState = DataListenerContainer<MusicLoadState>()

    private val page = 1
    private val size = 30

    fun getMusic() {
        //从model层获取音乐
        loadState.value = MusicLoadState.LOADING

        //从modeL层中获取音乐列表
        musicModel.loadMusicByPage(page, size, object : MusicsModel.onMusicLoadResult {
            override fun onSuccess(result: List<Music>) {
                musicList.value = result
                liveMusicList.postValue(result)
                loadState.value = if (result.isEmpty())
                    MusicLoadState.EMPTY
                else
                    MusicLoadState.SUCCESS
            }

            override fun onError(msg: String, code: Int) {
                loadState.value = MusicLoadState.ERROR
                Log.i("aaaaa", "error...$msg...$code")
            }
        })
    }

    /**
     * 被动通知View层的生命周期变化
     */
    inner class ViewLifeImpl : LifecycleEventObserver {

        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_START -> {
                    //监听GPS信号变化
                    Log.i("aaaaa", "监听GPS信号变化")
                }

                Lifecycle.Event.ON_STOP -> {
                    //停止GPS信号变化监听
                    Log.i("aaaaa", "停止GPS信号变化监听")
                }

                else -> {

                }
            }
        }
    }
}